import { Button, Card, Col, DatePicker, Descriptions, Input, List, message, Modal, Row, Select, Tabs, Tag } from "antd";

import { useEffect, useState } from "react";
import {
    PhoneOutlined,
    ClockCircleOutlined,
    CheckCircleOutlined,
    CloseCircleOutlined,
    ShoppingOutlined,
    CalendarOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
const { TabPane } = Tabs; // 从 Tabs 中解构 TabPane，这是 AntD 推荐用法


// 常量映射：数字类型转文本+样式（与Props数据匹配）
const CUSTOMER_TYPE_MAP = {
    0: { text: "潜在客户", color: "purple" },
    1: { text: "正式客户", color: "geekblue" },
    2: { text: "公海客户", color: "orange" }
};
const FOLLOW_STATUS_MAP = {
    0: { text: "待跟进", color: "orange", icon: <ClockCircleOutlined /> },
    1: { text: "跟进中", color: "processing", icon: <ClockCircleOutlined /> },
    2: { text: "已成交", color: "green", icon: <CheckCircleOutlined /> },
    3: { text: "已放弃", color: "red", icon: <CloseCircleOutlined /> }
};

// 客户详情模态框组件
export const CustomerDetails = (props) => {
    const customer=props.data;
  
    console.log(customer,';;;')
    // 状态管理：跟进表单、加载态、模态框显隐
    const [loading, setLoading] = useState(false);
    const [followUpVisible, setFollowUpVisible] = useState(false);
    const [followUpForm, setFollowUpForm] = useState({
        content: '',
        nextDate: null,
        status: customer?.status || 0 // 初始值绑定客户当前状态（数字）
    });
    // 存储跟进记录（初始为空，新增后通过父组件回调更新）
    const [followUpRecords, setFollowUpRecords] = useState([]);

    // 1. 客户数据变化时同步表单状态和跟进记录
    useEffect(() => {
        if (customer) {
            // 同步客户当前状态到表单
            setFollowUpForm(prev => ({ ...prev, status: customer.status }));
            // 若客户自带跟进记录，初始化到状态中（适配后续可能的后端返回）
            if (customer.followUpRecords) setFollowUpRecords(customer.followUpRecords);
        }
    }, [customer]);

    // 2. 处理跟进表单输入变化
    const handleFormChange = (key, value) => {
        setFollowUpForm({ ...followUpForm, [key]: value });
    };

    // 3. 提交跟进记录（调用父组件回调更新数据）
    const handleSubmitFollowUp = () => {
        if (!followUpForm.content.trim()) {
            message.error('请输入跟进内容');
            return;
        }

        setLoading(true);
        // 模拟API请求延迟
        setTimeout(() => {
            // 构造新的跟进记录
            const newFollowRecord = {
                id: `F${Date.now()}`,
                content: followUpForm.content,
                time: dayjs().format('YYYY-MM-DD HH:mm'),
                follower: customer.followUpPerson || '未分配',
                status: followUpForm.status, // 存储数字状态
                statusText: FOLLOW_STATUS_MAP[followUpForm.status].text // 文本状态（用于显示）
            };

            // 本地更新跟进记录列表
            setFollowUpRecords(prev => [newFollowRecord, ...prev]);
          

            // 重置表单并关闭模态框
            setFollowUpVisible(false);
            setFollowUpForm({ content: '', nextDate: null, status: customer.status });
            setLoading(false);
            message.success('跟进记录已保存');
        }, 800);
    };

    // 若未传入客户数据，不渲染组件
    if (!customer) return null;

    // ---------------------- 辅助渲染函数 ----------------------
    // 渲染客户类型标签（数字转带样式的标签）
    const renderCustomerType = () => {
        const typeConfig = CUSTOMER_TYPE_MAP[customer.type] || { text: "未知类型", color: "default" };
        return <Tag color={typeConfig.color}>{typeConfig.text}</Tag>;
    };

    // 渲染跟进状态标签（数字转带图标+样式的标签）
    const renderStatusTag = (status) => {
        const statusConfig = FOLLOW_STATUS_MAP[status] || { text: "未知状态", color: "default", icon: <ClockCircleOutlined /> };
        return <Tag color={statusConfig.color} icon={statusConfig.icon}>{statusConfig.text}</Tag>;
    };

    // 格式化金额（保留2位小数）
    const formatMoney = (amount) => Number(amount).toFixed(2);

    // ---------------------- 组件核心渲染 ----------------------
    return (
        <div className="modal-box">
            <Tabs defaultActiveKey="base" animated tabBarStyle={{ marginBottom: 20 }}>
                {/* 1. 基本信息标签页（所有客户通用） */}
                <TabPane tab="基本信息" key="base">
                    <Card>
                        <Row gutter={[24, 24]}>
                            {/* 左侧：身份与基础信息 */}
                            <Col xs={24} sm={12}>
                                <Descriptions
                                    column={1}
                                    bordered
                                    title="身份信息"
                                    titleStyle={{ fontSize: 14, fontWeight: 500 }}
                                >
                                    <Descriptions.Item label="客户姓名" labelStyle={{ width: 80 }}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                                            {customer.name}
                                            {customer.gender && (
                                                <Tag size="small" color="default">{customer.gender === '男' ? '先生' : '女士'}</Tag>
                                            )}
                                        </div>
                                    </Descriptions.Item>
                                    <Descriptions.Item label="联系电话" labelStyle={{ width: 80 }}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                                            <PhoneOutlined style={{ color: '#1890ff' }} />
                                            {customer.phone}
                                        </div>
                                    </Descriptions.Item>
                                    <Descriptions.Item label="客户类型" labelStyle={{ width: 80 }}>
                                        {renderCustomerType()}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="客户来源" labelStyle={{ width: 80 }}>
                                        <Tag color="blue" size="small">{customer.source}</Tag>
                                    </Descriptions.Item>
                                    <Descriptions.Item label="是否注册" labelStyle={{ width: 80 }}>
                                        {customer.registered ? (
                                            <Tag color="green" icon={<CheckCircleOutlined />}>已注册</Tag>
                                        ) : (
                                            <Tag color="default" icon={<CloseCircleOutlined />}>未注册</Tag>
                                        )}
                                    </Descriptions.Item>
                                </Descriptions>
                            </Col>

                            {/* 右侧：跟进与消费概览 */}
                            <Col xs={24} sm={12}>
                                <Descriptions
                                    column={1}
                                    bordered
                                    title={customer.type === 1 ? "消费跟进信息" : "跟进信息"}
                                    titleStyle={{ fontSize: 14, fontWeight: 500 }}
                                >
                                    <Descriptions.Item label="跟进状态" labelStyle={{ width: 80 }}>
                                        {renderStatusTag(customer.status)}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="跟进人" labelStyle={{ width: 80 }}>
                                        {customer.followUpPerson || <span style={{ color: '#999' }}>未分配</span>}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="上次跟进" labelStyle={{ width: 80 }}>
                                        {customer.lastFollowUp !== '-' ? customer.lastFollowUp : <span style={{ color: '#999' }}>未跟进</span>}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="下次跟进" labelStyle={{ width: 80 }}>
                                        {customer.nextFollowUp !== '-' ? (
                                            <span style={{ color: dayjs(customer.nextFollowUp) < dayjs() ? '#f53f3f' : '#1890ff' }}>
                                                {customer.nextFollowUp}
                                            </span>
                                        ) : (
                                            <span style={{ color: '#999' }}>未设置</span>
                                        )}
                                    </Descriptions.Item>
                                    {/* 正式客户额外显示消费概览 */}
                                    {customer.type === 1 && (
                                        <Descriptions.Item label="累计消费" labelStyle={{ width: 80 }}>
                                            <span style={{ color: '#f53f3f', fontWeight: 500 }}>¥{formatMoney(customer.totalConsumption)}</span>
                                        </Descriptions.Item>
                                    )}
                                </Descriptions>
                            </Col>
                        </Row>

                     
                    </Card>
                </TabPane>

                {/* 2. 差异化标签页：潜在/公海客户显示「跟进记录」，正式客户显示「消费记录」 */}
                {(customer.type === 0 || customer.type === 2) ? (
                    <TabPane tab="跟进记录" key="followUp">
                        <Card bordered={false}>
                            {/* 跟进记录列表 */}
                            {followUpRecords.length > 0 ? (
                                <List
                                    itemLayout="vertical"
                                    dataSource={followUpRecords.sort((a, b) => new Date(b.time) - new Date(a.time))} // 按时间倒序
                                    renderItem={item => (
                                        <List.Item
                                            key={item.id}
                                            extra={
                                                <div style={{ textAlign: 'right' }}>
                                                    {renderStatusTag(item.status)}
                                                    <div style={{ marginTop: 8, color: '#666', fontSize: 12 }}>
                                                        {item.time}
                                                    </div>
                                                    <div style={{ marginTop: 4, color: '#888', fontSize: 12 }}>
                                                        跟进人：{item.follower}
                                                    </div>
                                                </div>
                                            }
                                            style={{ borderBottom: '1px dashed #f0f0f0', paddingBottom: 16, marginBottom: 16 }}
                                        >
                                            <List.Item.Meta
                                                title={<span style={{ fontSize: 14, fontWeight: 500 }}>跟进内容</span>}
                                                description={<p style={{ lineHeight: 1.6 }}>{item.content}</p>}
                                            />
                                        </List.Item>
                                    )}
                                />
                            ) : (
                                <div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
                                    <ClockCircleOutlined style={{ fontSize: 32, marginBottom: 12 }} />
                                    <p>暂无跟进记录，点击「记录跟进」添加第一条记录</p>
                                </div>
                            )}

                            {/* 新增跟进按钮 */}
                            <div style={{ textAlign: 'right' }}>
                                <Button
                                    type="primary"
                                    icon={<PhoneOutlined />}
                                    onClick={() => setFollowUpVisible(true)}
                                >
                                    新增跟进记录
                                </Button>
                            </div>
                        </Card>
                    </TabPane>
                ) : (
                    <TabPane tab="消费记录" key="consumption">
                        <Card bordered={false}>
                            {/* 消费记录列表 */}
                            {customer.consumedServices.length > 0 ? (
                                <List
                                    itemLayout="vertical"
                                    dataSource={customer.consumedServices.map((service, index) => ({
                                        // 基于客户已有消费项目构造消费记录（适配Props数据结构）
                                        id: `C${customer.customerNo.slice(-4)}${index + 1}`,
                                        product: service,
                                        amount: customer.totalConsumption / customer.consumedServices.length, // 平均分配总消费
                                        date: dayjs().subtract(index + 1, 'month').format('YYYY-MM-DD'), // 生成递减日期
                                        status: '已付款'
                                    })).sort((a, b) => new Date(b.date) - new Date(a.date))} // 按时间倒序
                                    renderItem={item => (
                                        <List.Item
                                            key={item.id}
                                            extra={
                                                <div style={{ textAlign: 'right' }}>
                                                    <span style={{ fontSize: 16, fontWeight: 'bold', color: '#3f8600' }}>
                                                        ¥{formatMoney(item.amount)}
                                                    </span>
                                                    <div style={{ marginTop: 8 }}>
                                                        <Tag color="green">{item.status}</Tag>
                                                    </div>
                                                </div>
                                            }
                                            style={{ borderBottom: '1px dashed #f0f0f0', paddingBottom: 16, marginBottom: 16 }}
                                        >
                                            <List.Item.Meta
                                                title={item.product}
                                                description={
                                                    <div style={{ lineHeight: 1.6 }}>
                                                        <p>消费日期: {item.date}</p>
                                                        <p>订单编号: {item.id}</p>
                                                    </div>
                                                }
                                            />
                                        </List.Item>
                                    )}
                                />
                            ) : (
                                <div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
                                    <ShoppingOutlined style={{ fontSize: 32, marginBottom: 12 }} />
                                    <p>暂无消费记录，点击「添加消费记录」创建第一条记录</p>
                                </div>
                            )}
                        </Card>
                    </TabPane>
                )}

             
            </Tabs>

            {/* 跟进记录表单模态框 */}
            <Modal
                title="记录跟进信息"
                open={followUpVisible}
                onCancel={() => setFollowUpVisible(false)}
                onOk={handleSubmitFollowUp}
                confirmLoading={loading}
                destroyOnHidden={true}
                width={500}
            >
                <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>
                        跟进内容 <span style={{ color: '#f53f3f' }}>*</span>
                    </label>
                    <Input.TextArea
                        rows={4}
                        value={followUpForm.content}
                        onChange={(e) => handleFormChange('content', e.target.value)}
                        placeholder="请输入本次跟进的详细内容（如客户反馈、沟通结果等）"
                        autoSize={{ minRows: 4, maxRows: 6 }}
                    />
                </div>

                <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>
                        客户状态
                    </label>
                    <Select
                        style={{ width: '100%' }}
                        value={followUpForm.status}
                        onChange={(value) => handleFormChange('status', value)}
                        options={[
                            { value: 0, label: FOLLOW_STATUS_MAP[0].text },
                            { value: 1, label: FOLLOW_STATUS_MAP[1].text },
                            { value: 2, label: FOLLOW_STATUS_MAP[2].text },
                            { value: 3, label: FOLLOW_STATUS_MAP[3].text }
                        ]}
                    />
                </div>

                <div>
                    <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>
                        下次跟进时间
                    </label>
                    <DatePicker
                        style={{ width: '100%' }}
                        value={followUpForm.nextDate ? dayjs(followUpForm.nextDate) : null}
                        onChange={(date) => handleFormChange('nextDate', date ? date.format('YYYY-MM-DD') : null)}
                        placeholder="选择下次跟进时间（可选）"
                        icon={<CalendarOutlined />}
                        disabledDate={(current) => current && current < dayjs().startOf('day')} // 禁止选择过去日期
                    />
                </div>
            </Modal>
        </div>
    );
};